package com.webserver.controller;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.webserver.vo.Article;

import java.io.*;

/**
 * 处理与文章相关的业务
 * @Author Alex
 */
public class ArticleController {
    //所有用户信息所保存的目录
    public static final String ARTICLE_DIR = "./articles/";

    static{
        File dir =new File(ARTICLE_DIR);
        if (!dir.exists()){
            dir.mkdirs();
        }
    }

    public void writeArticle(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始发表文章");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");

        if (title==null||author==null||content==null){
            File file = new File("./webapps/myweb/article_fail.html");
            response.setEntity(file);
            return;
        }

        try (
                FileOutputStream fos = new FileOutputStream(ARTICLE_DIR+title+".obj");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            Article article = new Article(title,author,content);
            oos.writeObject(article);
            File file = new File("./webapps/myweb/article_success.html");
            response.setEntity(file);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("文章发表处理完毕");
    }
}
